package com.shinhye.mobilelottery.ui;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Random;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;

import com.shinhye.mobilelottery.ConstantValue;
import com.shinhye.mobilelottery.R;
import com.shinhye.mobilelottery.bean.ShoppingCart;
import com.shinhye.mobilelottery.bean.Ticket;
import com.shinhye.mobilelottery.engine.CommonInfoEngine;
import com.shinhye.mobilelottery.net.protocol.Message;
import com.shinhye.mobilelottery.net.protocol.Oelement;
import com.shinhye.mobilelottery.net.protocol.element.IssueInfoElement;
import com.shinhye.mobilelottery.ui.adapter.PoolAdapter;
import com.shinhye.mobilelottery.ui.custom.MyGridView;
import com.shinhye.mobilelottery.ui.custom.MyGridView.OnTouchActionListener;
import com.shinhye.mobilelottery.ui.manager.BottomManager;
import com.shinhye.mobilelottery.ui.manager.MiddleManager;
import com.shinhye.mobilelottery.ui.manager.PlayGame;
import com.shinhye.mobilelottery.ui.manager.TitleManager;
import com.shinhye.mobilelottery.ui.sensor.ShakeListener;
import com.shinhye.mobilelottery.utils.BeanFactory;
import com.shinhye.mobilelottery.utils.PromptManager;

public class PlaySSQUI extends BaseUI implements OnClickListener, PlayGame {
	private final int red_total = 33;
	private final int blue_total = 16;
	private final int red_max = 18;
	private final int blue_max = 6;
	private MyGridView redGrid;
	private GridView blueGrid;
	private ArrayList<Integer> redNum;
	private ArrayList<Integer> blueNum;
	private PoolAdapter redAdapter;
	private PoolAdapter blueAdapter;
	private Button redrandom;
	private Button bluerandom;
	private SensorManager sm;
	private SensorEventListener listener;

	public PlaySSQUI(Context context) {
		super(context);
	}
	// 通用三步
	// 三个容器联动
	// 工作清单
	// ①标题处理
	// ②填充选号容器（红球与蓝球）
	// ③处理选号（单选+机选）
	// 单选处理
	// 左右摇晃
	// 放大效果的实现
	
	// ④手机摇晃处理
	// ⑤底部导航处理（提示信息+清空+选好了）
	@Override
	protected void onCreate() {
		View showView = View.inflate(getContext(), R.layout.il_playssq, null);
		redGrid = (MyGridView) showView.findViewById(R.id.ii_ssq_red_number_container);
		blueGrid = (GridView) showView.findViewById(R.id.ii_ssq_blue_number_container);
		redrandom = (Button) showView.findViewById(R.id.ii_ssq_random_red);
		bluerandom = (Button) showView.findViewById(R.id.ii_ssq_random_blue);
		
		redNum = new EnhancedList<Integer>(red_max);
		blueNum = new EnhancedList<Integer>(blue_max);
		
		redAdapter = new PoolAdapter(getContext(), red_total, redNum, R.drawable.id_redball);
		blueAdapter = new PoolAdapter(getContext(), blue_total, blueNum, R.drawable.id_blueball);
		
		redGrid.setAdapter(redAdapter);
		blueGrid.setAdapter(blueAdapter);
		
		setContentView(showView);
		
		sm = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
	}

	@Override
	protected void setListener() {
		//直接redGrid.setOnTouchListener也可以实现，而且省去了自定义控件
		redGrid.setOnTouchActionListener(new OnTouchActionListener() {
			@Override
			public void onActionUp(View view, int position) {
				if(!redNum.contains(position)) {
					boolean add_succ = redNum.add(position);
					if(add_succ) {
						view.setBackgroundResource(R.drawable.id_redball);
					} else {
						Toast.makeText(getContext(), "超过红球个数上限！", Toast.LENGTH_SHORT).show();
					}
				} else {
					redNum.remove((Integer) position);
					view.setBackgroundResource(R.drawable.id_defalut_ball);
				}
				
//				changeNotice();
			}
			@Override
			public void onActionDown(View view, int position) {}
			@Override
			public void onActionMove(View view, int position) {}
		});
		
		blueGrid.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(!blueNum.contains(position)) {
					boolean add_succ = blueNum.add(position);
					if(add_succ) {
						view.setBackgroundResource(R.drawable.id_blueball);
						Animation anim = AnimationUtils.loadAnimation(getContext(), R.anim.ia_ball_shake);
						view.startAnimation(anim);
					} else {
						Toast.makeText(getContext(), "超过蓝球个数上限！", Toast.LENGTH_SHORT).show();
					}
				} else {
					blueNum.remove((Integer) position);
					view.setBackgroundResource(R.drawable.id_defalut_ball);
				}
				
//				changeNotice();
			}
		});
		
		redrandom.setOnClickListener(this);
		bluerandom.setOnClickListener(this);
	}

	@Override
	public int getId() {
		return ConstantValue.VIEW_PLAYSSQ;
	}
	
	@Override
	public void onResume() {
		changeTitle();
		clear();
		
		listener = new ShakeListener(getContext()) {
			@Override
			public void shaked() {
				Random random = new Random();
				redNum.clear();
				blueNum.clear();
				
				while(redNum.size() < 6) {
					int redpos = random.nextInt(red_total);
					if(redNum.contains(redpos))
						continue;
					redNum.add(redpos);
				}
				int bludepos = (int) (random.nextDouble() * blue_total);
				blueNum.add(bludepos);
				
				redAdapter.notifyDataSetChanged();
				blueAdapter.notifyDataSetChanged();
				
//				changeNotice();
			}
		};
		
		//注册加速传感器
		sm.registerListener(listener, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
	}
	
	@Override
	public void onPause() {
		//注销加速传感器
		sm.unregisterListener(listener);
	}

	@Override
	public void clear() {
		redNum.clear();
		blueNum.clear();
		
		redAdapter.notifyDataSetChanged();
		blueAdapter.notifyDataSetChanged();
		
		changeNotice();
	}
	
	@Override
	public void done() {
		// 与购彩业务相关：购物车
		// 购物车中仅能放置一个彩种当前期的投注

		// 判断：用户是否选择了一注投注
		// 判断：是否获取到当前销售期信息

		// 封装用户投注信息：红球+蓝球+注数
		// 创建购物车，将投注信息添加到购物车中
		// 购物车特有数据设置
		// 界面跳转到购物车展示界面

		// 分支工作
		// 提示用户：需要选择一注投注
		// 重新到服务器端获取
		
		if(redNum.size() >= 6 && blueNum.size() >= 1) {
			if(getBundle() != null) {
				Ticket ticket = new Ticket();
				DecimalFormat format = new DecimalFormat("00");
				StringBuffer sb = new StringBuffer();
				for(int num : redNum) {
					String str = format.format(num);
					sb.append(str + " ");
				}
				ticket.setRedNum(sb.toString().trim());
				sb = new StringBuffer();
				for(int num : blueNum) {
					String str = format.format(num);
					sb.append(str + " ");
				}
				ticket.setBlueNum(sb.toString().trim());
				ticket.setRecord(calc());
				
				ShoppingCart intance = ShoppingCart.getInstance();
				intance.setLotteryid(ConstantValue.SSQ);
				intance.setIssue(getBundle().getString("issue"));
				intance.getTicketBag().add(ticket);
				
				MiddleManager.getInstance().changeUI(OrderUI.class, getBundle());
			} else {
				getIssueInfo();
			}
		} else {
			Toast.makeText(getContext(), "需要选择一注投注", Toast.LENGTH_SHORT).show();
		}
	}
	
	private void getIssueInfo() {
		new MyAsyncTask<Integer>() {
			@Override
			protected void onPreExecute() {
				PromptManager.showProgressDialog(getContext());
			};
			
			@Override
			protected Message doInBackground(Integer... params) {
				int id = params[0];
				CommonInfoEngine infoEngine = BeanFactory.getImpl(CommonInfoEngine.class);
				Message res = infoEngine.getIssuesInfo(id);
				return res;
			}

			@Override
			protected void onPostExecute(Message result) {
				PromptManager.closeProgressDialog();
				if(result == null)
					return;
				
				Oelement oelement = result.getBody().getOelement();
				if(ConstantValue.SUCCESS.equals(oelement.getErrorcode())) {
					IssueInfoElement element = (IssueInfoElement) result.getBody().getElements().get(0);
					Bundle bundle = new Bundle();
					bundle.putString("issue", element.getIssue().getValue());
					setBundle(bundle);
					
					changeTitle();
				} else {
					PromptManager.showErrorDialog(getContext(), oelement.getErrormsg());
				}
			}
		}.execute(ConstantValue.SSQ);
	}

	private void changeTitle() {
		Bundle bundle = getBundle();
		String issue = "";
		String title = "";
		if(bundle != null) {
			issue = bundle.getString("issue");
		}
		if(TextUtils.isEmpty(issue)) {
			title = "双色球选号";
		} else {
			title = "双色球第" + bundle.getString("issue") + "期选号";
		}
		TitleManager.getInstance().changeTitle(title);
	}
	
	//机选按钮
	@Override
	public void onClick(View v) {
		Random random = new Random();
		switch(v.getId()) {
		case R.id.ii_ssq_random_red:
			redNum.clear();
			while(redNum.size() < 6) {
				int redpos = random.nextInt(red_total);
				if(redNum.contains(redpos))
					continue;
				redNum.add(redpos);
			}
			redAdapter.notifyDataSetChanged();
		break;
		case R.id.ii_ssq_random_blue:
			blueNum.clear();
			int bludepos = (int) (random.nextDouble() * blue_total);
			blueNum.add(bludepos);
			blueAdapter.notifyDataSetChanged();
		break;
		}
//		changeNotice();
	}

	private void changeNotice() {
		String bottominfo;
		if(redNum.size() < 6)
			bottominfo = "还需选择" + (6 - redNum.size()) + "个红球";
		else if(blueNum.size() == 0)
			bottominfo = "还需选择1个蓝球";
		else {
			int record = calc();
			bottominfo = "共" + record + "注" + 2 * record + "元";
		}
		
		BottomManager.getInstance().changeGameBottomNotice(bottominfo);
	}
	
	/**
	 * Calculate the record number.
	 * @return
	 */
	private int calc() {
		int redRecord = (int) (factorial(redNum.size()) / (factorial(6) * factorial(redNum.size() - 6)));
		int blueRecord = blueNum.size();
		return redRecord * blueRecord;
	}
	
	private long factorial(int n) {
		if(n > 1) {
			return n * factorial(n - 1);
		} else if(n == 1 || n == 0) {
			return 1;
		} else {
			throw new IllegalArgumentException("输入的参数不对！");
		}
	}
	
	class EnhancedList<T> extends ArrayList<T> {
		private static final long serialVersionUID = -5421215297233906483L;
		private int max;
		public EnhancedList(int max) {
			super();
			this.max = max;
		}
		
		@Override
		public boolean add(T object) {
			if(this.size() < max) {
				super.add(object);
				changeNotice();
				return true;
			}
			return false;
		}
		
		@Override
		public boolean remove(Object object) {
			boolean b = super.remove(object);
			changeNotice();
			return b;
		}
	}
}
